<?php

namespace User;

use C\L\WebController;
use C\M\Message;

class MessageController extends WebController
{
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);

        $userId = $this->uid;

        $items = $this->s_message->listUserMessages($userId, $currentPage, $perPage);

        $pagination = [
            'current_page' => $currentPage,
            'per_page'     => $perPage,
        ];

        return $this->success(compact('items', 'pagination'));
    }

    public function showAction()
    {
        $id = $this->request->getQuery('id', 'int', 0);

        $message = Message::findById($id);
        if (!$message) {
            return $this->error('未找到该站内信');
        }

        return $this->success($message->toArray());
    }

    public function unreadAction()
    {
        $id = $this->request->getPost('id', 'int', 0);
        $userId = $this->uid;

        return $this->s_message->unread($userId, $id)
            ? $this->success()
            : $this->error();
    }

    public function readAction()
    {
        $id = $this->request->getPost('id', 'int', 0);
        $userId = $this->uid;

        return $this->s_message->read($userId, $id)
            ? $this->success()
            : $this->error();
    }

    public function deleteAction()
    {
        $id = $this->request->getPost('id', 'int', 0);
        $userId = $this->uid;

        return $this->s_message->deleteLog($userId, $id)
            ? $this->success()
            : $this->error();
    }
}
